package com.timing.feedback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.timing.feedback.entity.UserPO;
import com.timing.feedback.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author cwh
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    /**
     * 通过名称加载用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username==null||"".equals(username)){
            throw new RuntimeException("用户名或密码不能为空");
        }
        //根据用户名查询用户信息
        LambdaQueryWrapper<UserPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPO::getUsername,username);
        UserPO user = userMapper.selectOne(wrapper);
        if(user == null){
            throw new UsernameNotFoundException(String.format("%s用户不存在",username));
        }
        return new UserPO(user.getId(),user.getUsername(),user.getPassword());
    }
}
